let request = require('request');
let path = require('path');
let fs = require('fs');
let ffmpeg = require('fluent-ffmpeg');

var log4js = require('log4js');
var logger = log4js.getLogger('leewind');
logger.level = 'debug';

const DOUBAN_FM_URL =
  'https://fm.douban.com/j/v2/playlist?channel=10687&kbps=192&client=s:mainsite|y:3.0&app_name=radio_website&version=100&type=n'
// 'https://douban.fm/j/v2/playlist?channel=3925605&kbps=128&client=s%3Amainsite%7Cy%3A3.0&app_name=radio_website&version=100&type=n';
const DEFAULT_COOKIE =
  // '_vwo_uuid_v2=E9172C006FC9DA6B1EE3F6CBD8E99EFE|bf66fa2e76cfa24fbe39615216a3b1ab; gr_user_id=4f1abd2f-fce2-49f4-bfb5-686b0167b205; douban-fav-remind=1; viewed="27116728_30261633_27178073_27056409_26178426_27608239_27602003"; douban-profile-remind=1; ue="leewind841209@163.com"; __utmv=30149280.13877; __utma=30149280.1782470181.1526199569.1534608310.1535383999.7; __utmz=30149280.1535383999.7.5.utmcsr=google|utmccn=(organic)|utmcmd=organic|utmctr=(not%20provided); bid=NENDHt85yQM; dbcl2="138779695:dOQWTGxPHKU"; ck=FKxo; _ga=GA1.2.1782470181.1526199569; _gid=GA1.2.1704170296.1548934414; _gat=1'
  'bid=3X0HmmOusGE; _ga=GA1.2.1179885582.1510886290; flag="ok"; dbcl2="138779695:ciiZ0QKOulo"; ck=q64x; _gid=GA1.2.1188758659.1517755975';
const timeout = 10000;

let count = 0;

function requestSong(cookie) {
  var cookieInfo = request.jar();
  var cookie = request.cookie(DEFAULT_COOKIE);
  var url = 'http://www.google.com';
  cookieInfo.setCookie(cookie, DOUBAN_FM_URL);

  request.cookie(DEFAULT_COOKIE);
  request.get(
    {
      url: DOUBAN_FM_URL,
      jar: cookieInfo
    },
    function (error, response, body) {
      if (error) {
        logger.error(error);
        return setTimeout(requestSong, timeout);
      }

      logger.info(body);

      let bodyJson = JSON.parse(body);
      if (bodyJson.song.length > 0) {
        count = bodyJson.song.length;
        for (var index = 0; index < bodyJson.song.length; index++) {
          var element = bodyJson.song[index];

          let songg = element.title + ' - ' + element.artist + '.' + element.file_ext

          let filepath = path.join(
            __dirname,
            '/download',
            songg
          );

          if (!fs.exists(filepath)) {
            downloadSong(element.url, filepath, element.title + ' - ' + element.artist, () => {
              count--;
              if (count <= 0) {
                return setTimeout(requestSong, timeout);
              }
            });
          } else {
            logger.info(
              song + '已经存在，跳过'
            );

            count--;
            if (count <= 0) {
              return setTimeout(requestSong, timeout);
            }
          }
        }
      }
    }
  );
}

function downloadSong(uri, filepath, filename, callback) {
  var stream = fs.createWriteStream(filepath);
  var target = '/Users/leewind/Projects/leewind/node_spider_douban_fm/mp3/' + filename + '.mp3'

  if (fs.exists(target)) { callback(); }

  request(uri)
    .pipe(stream)
    .on('close', function () {
      setTimeout(() => {
        try {
          ffmpeg(filepath)
            .clone()
            .format('mp3')
            .saveToFile(target);
          logger.info('下载完成：' + count + ' - ' + filename + '.mp3');
        } finally {
          callback();
        }
      }, 5000);
    });
}

var fetch = function () {
  try {
    requestSong();
  }
  catch (e) {
    fetch()
  }
}

fetch()
